#include "Input.h"

POINT Input::cursorPosition;
POINT Input::cursorRelPos;
Key Input::keys[256];
Key Input::prevKeys[256];

CRITICAL_SECTION Input::criticalSection;

bool Input::Init()
{
	ZeroMemory((void*)&keys,sizeof(Key)*256);
	ZeroMemory((void*)&prevKeys,sizeof(Key)*256);

	InitializeCriticalSection(&criticalSection);

	cursorRelPos.x = 0;
	cursorRelPos.y = 0;

	cursorPosition.x = 0;
	cursorPosition.y = 0;
	
	return true;
}

void Input::ClearKeys()
{
	ZeroMemory((void*)&keys,sizeof(Key)*256);

	cursorRelPos.x = 0;
	cursorRelPos.y = 0;
}

void Input::RawKeyInput(RAWKEYBOARD& kb)
{
	EnterCriticalSection(&criticalSection);

	if(kb.Message == WM_KEYDOWN)
	{
		keys[kb.VKey].down = true;
	}
	if(kb.Message == WM_KEYUP)
	{
		keys[kb.VKey].down = false;
	}

	LeaveCriticalSection(&criticalSection);
}

void Input::RawMouseInput(RAWMOUSE& mouse)
{
	cursorRelPos.x = mouse.lLastX;
	cursorRelPos.y = mouse.lLastY;

	cursorPosition.x+=mouse.lLastX;
	cursorPosition.y+=mouse.lLastY;
}

bool Input::KeyDown(char _keyCode)
{
	EnterCriticalSection(&criticalSection);
	bool result = keys[_keyCode].down;
	LeaveCriticalSection(&criticalSection);

	return result;
}

bool Input::KeyPressed(char _keyCode)
{
	EnterCriticalSection(&criticalSection);
	bool result = keys[_keyCode].down && !prevKeys[_keyCode].down;
	LeaveCriticalSection(&criticalSection);

	return result;
}

bool Input::KeyReleased(char _keyCode)
{
	EnterCriticalSection(&criticalSection);
	bool result = !keys[_keyCode].down && prevKeys[_keyCode].down;
	LeaveCriticalSection(&criticalSection);
	
	return result;
}

void Input::Update()
{
	EnterCriticalSection(&criticalSection);
	memcpy(prevKeys, keys, 256);
	LeaveCriticalSection(&criticalSection);
}